package com.bbzn.device.client.controller;

import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.vo.req.ProductVO;
import com.bbzn.device.client.aspect.OperationAnnotation;
import com.bbzn.device.client.constant.PageConstant;
import com.bbzn.device.client.constant.ProductConstant;
import com.bbzn.device.client.dataobject.DeviceCategory;
import com.bbzn.device.client.dataobject.Product;
import com.bbzn.device.client.dataobject.ProductType;
import com.bbzn.device.client.dataobject.SystemParam;
import com.bbzn.device.client.dto.api.ct.response.ResponseBase;
import com.bbzn.device.client.dto.device.DeviceDTO;
import com.bbzn.device.client.dto.product.ProductDTO;
import com.bbzn.device.client.exception.DefinitException;
import com.bbzn.device.client.service.*;
import com.bbzn.device.client.utils.*;
import com.ctg.ag.sdk.biz.aep_product_management.DeleteProductResponse;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @Author 黄志鹏
 * @Date 2021/3/16 17:11
 * @Version 1.0
 */

@RestController
@RequestMapping("/product")
@Slf4j
//@CrossOrigin
public class ProductController extends BaseApiService {


    @Autowired
    private SystemParamByCacheService systemParamByCacheService;

    @Autowired
    private ProductService productService;

    @Autowired
    private CommonService commentService;

    @Autowired
    private DeviceCategoryService deviceCategoryService;

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ProductManagementService productManagementService;

    @Autowired
    private ProductTypeService productTypeService;

    /**
     * 查询产品列表
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getProductList", method = RequestMethod.POST)
    @OperationAnnotation(content = "查询产品列表")
    public BaseResponse getProductList(@RequestBody ProductVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getPageSize()).isPresent()) {
            reqVO.setPageSize(PageConstant.PAGE_SIZE);
        }
        if (!OptionalBean.ofNullable(reqVO.getPageNum()).isPresent()) {
            reqVO.setPageNum(PageConstant.PAGE_NUM);
        }
        ProductDTO query = new ProductDTO();
        BeanUtils.copyProperties(reqVO, query);
        if (null != reqVO.getPageNum()) {
            query.setPageNum(reqVO.getPageNum());
        }
        if (null != reqVO.getPageSize()) {
            query.setPageSize(reqVO.getPageSize());
        }
        query.setStartIndex((reqVO.getPageNum() - 1) * reqVO.getPageSize());
        PageInfo<Product> products = productService.findAllPageSelective(query);
        return setResultSuccess(products);
    }

    /**
     * 根据产品ID查询对应数据
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getProduct", method = RequestMethod.POST)
    @OperationAnnotation(content = "根据产品ID查询对应数据")
    public BaseResponse getProduct(@RequestBody ProductVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        Product product = productService.selectByPrimaryKey(reqVO.getId());
        return setResultSuccess(product);
    }

    /**
     * 新增产品
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addProduct", method = RequestMethod.POST)
    @OperationAnnotation(content = "新增产品信息")
    public BaseResponse addProduct(@RequestBody ProductVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commentService.getUserId(request);
        if (!OptionalBean.ofNullable(reqVO.getPageSize()).isPresent()) {
            reqVO.setPageSize(PageConstant.PAGE_SIZE);
        }
        if (!OptionalBean.ofNullable(reqVO.getPageNum()).isPresent()) {
            reqVO.setPageNum(PageConstant.PAGE_NUM);
        }
        if (!OptionalBean.ofNullable(reqVO.getProductName()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PRONAME_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getPid()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getStatus()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_STATE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        Product product = new Product();
        if (OptionalBean.ofNullable(reqVO.getRemark()).isPresent()) {
            product.setRemark(reqVO.getRemark());
        }
        //前端要用加的字段
        if (OptionalBean.ofNullable(reqVO.getNavigationBar()).isPresent()) {
            product.setNavigationBar(reqVO.getNavigationBar());
        }
        product.setProductName(reqVO.getProductName());
        product.setUpdateTime(new Date());
        product.setCreateTime(new Date());
        if (OptionalBean.ofNullable(reqVO.getImgUrl()).isPresent()) {
            product.setImgUrl(reqVO.getImgUrl());
        }
        if (OptionalBean.ofNullable(reqVO.getSort()).isPresent()) {
            product.setSort(reqVO.getSort());
        }
        if (OptionalBean.ofNullable(reqVO.getPid()).isPresent()) {
            product.setPid(reqVO.getPid());
        }
        product.setStatus(reqVO.getStatus());
        productService.insertSelective(product);
        if (OptionalBean.ofNullable(product.getId()).isPresent() && OptionalBean.ofNullable(reqVO.getSort()).isPresent()) {
            Product update = new Product();
            update.setSort(product.getId());
            update.setId(product.getId());
            productService.updateByPrimaryKeySelective(update);
        }
        systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_ADD_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 更新产品
     *
     * @param reqVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateProduct", method = RequestMethod.POST)
    @OperationAnnotation(content = "更新产品信息")
    public BaseResponse updateProduct(@RequestBody ProductVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commentService.getUserId(request);
        if (!OptionalBean.ofNullable(reqVO.getId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getProductName()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PRONAME_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getPid()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getStatus()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_STATE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        Product product = new Product();
        if (OptionalBean.ofNullable(reqVO.getRemark()).isPresent()) {
            product.setRemark(reqVO.getRemark());
        }
        if (OptionalBean.ofNullable(reqVO.getImgUrl()).isPresent()) {
            product.setImgUrl(reqVO.getImgUrl());
        }
        if (OptionalBean.ofNullable(reqVO.getSort()).isPresent()) {
            product.setSort(reqVO.getSort());
        }
        //前端要用加的字段
        if (OptionalBean.ofNullable(reqVO.getNavigationBar()).isPresent()) {
            product.setNavigationBar(reqVO.getNavigationBar());
        }
        product.setStatus(reqVO.getStatus());
        product.setPid(reqVO.getPid());
        product.setProductName(reqVO.getProductName());
        product.setId(reqVO.getId());
        product.setUpdateTime(new Date());
        productService.updateByPrimaryKeySelective(product);
        systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_UPDATA_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }


    /**
     * 删除产品(单个删除)
     * 删除产品数据，如果产品下有设备数据，则无法删除产品
     *
     * @param reqVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delProduct", method = RequestMethod.POST)
    @OperationAnnotation(content = "删除产品信息(单个删除)")
    public BaseResponse delProduct(@RequestBody ProductVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commentService.getUserId(request);
        if (!OptionalBean.ofNullable(reqVO.getId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        /**
         * 1： 该产品下是否有设备
         * 2： 该产品是否是NB产品
         */
        DeviceDTO query = new DeviceDTO();
        query.setProductId(reqVO.getId());
        int count = deviceService.findCountByAll(query);
        if (count > 0) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRODUCT_EXIST_DEVICE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        DeviceCategory queryCategory = new DeviceCategory();
        queryCategory.setProductId(reqVO.getId());
        List<DeviceCategory> deviceCategories = deviceCategoryService.findByAll(queryCategory);
        for (DeviceCategory deviceCategory : deviceCategories) {
            delNbDevice(deviceCategory);
        }
        productService.deleteByPrimaryKey(reqVO.getId());
        systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_DEL_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 调用电信删除NB设备接口
     *
     * @param category
     * @throws Exception
     */
    @OperationAnnotation(content = "调用电信删除NB设备接口")
    private void delNbDevice(DeviceCategory category) throws Exception {
        //NB产品
        if (category.getProType() == 1) {
            DeleteProductResponse deleteProductResponse = productManagementService.deleteProduct(category.getMasterKey(), category.getNbProductId().intValue());
            // 4.响应结果
            int code = deleteProductResponse.getStatusCode();
            if (code != 200) {
                throw new DefinitException(code, deleteProductResponse.getMessage());
            }
            byte[] retBody = deleteProductResponse.getBody();
            System.out.println(retBody);
            ResponseBase responseBase = JsonUtils.byteToJaveBean(retBody, ResponseBase.class);
            Integer resCode = responseBase.getCode();
            if (resCode != 0) {
                throw new DefinitException(resCode, responseBase.getMsg());
            }
        }
    }


    @ApiOperation(value = "获取NB产品一级分类", notes = "获取NB产品一级分类")
    @PostMapping("/queryProductType1")
    public BaseResponse<JSONObject> queryProductType1() {
        List<ProductType> productTypes = productTypeService.getProductType1();
        JSONObject data = new JSONObject();
        data.put("productTypes", productTypes);
        return setResultSuccess(data);
    }

    @ApiOperation(value = "获取产品二级，三级分类", notes = "获取产品二级，三级分类")
    @PostMapping("/queryProductType")
    public BaseResponse<JSONObject> queryProductType(HttpServletRequest request, @RequestBody ProductVO productVO) throws Exception {
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(productVO.getPid()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        List<ProductType> productTypes = productTypeService.getProductTypeBy1(productVO.getPid());
        JSONObject data = new JSONObject();
        data.put("productTypes", productTypes);
        return setResultSuccess(data);
    }
}
